package com.example;

import java.io.IOError;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Hello world!
 *
 */
public class App 
{
    private static int i = 0;
    private static final Queue<Integer> queue = new LinkedList<Integer>();

    public static void main(String[] args ) throws InterruptedException {
//        Thread thread01 = new Thread(() -> {
//            System.out.println("Thread 01 started");
//            int sum = 0;
//            for (int i = 0; i < 10; i++) {
//                sum += i;
//            }
//            System.out.println("Thread 01 finished");
//            System.out.println("Sum: " + sum);
//        });
//        thread01.start();
//        Thread thread02 = new Thread(() -> {
//            System.out.println("Thread 02 started");
//            int sum = 0;
//            for (int i = 0; i < 100; i++) {
//                sum += i;
//            }
//            System.out.println("Thread 02 finished");
//            System.out.println("Sum: " + sum);
//        });
//        thread02.start();\
//        Object o = new Object();
//        new Thread( () -> {
//            for (int j = 0; j < 10000; j++) {
//                synchronized (o) {
//                    i++;
//                }
//            }
//        }).start();
//
//        new Thread( () -> {
//            for (int j = 0; j < 10000; j++) {
//                synchronized (o) {
//                    i++;
//                }
//            }
//        }).start();
//        Thread.sleep(1000);
//        System.out.println(i);

        new Thread(App::add, "1").start();
        new Thread(App::add, "2").start();

    }

    public static void add() {
        while (true) {
            try {
                Thread.sleep(3000);
                synchronized (queue) {
                    String name = Thread.currentThread().getName();
                    System.out.println("厨师" + name + "出餐了");
                    queue.add(1);
                    queue.notifyAll();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void take() throws IOException, InterruptedException {
        while (true) {
            synchronized (queue) {
                while (queue.isEmpty()) {
                    queue.wait();
                }
                queue.poll();
                String name = Thread.currentThread().getName();
                System.out.println("消费者" + name + "拿到餐品");
                Thread.sleep(4000);
            }

        }
    }

}
